/*
 * Adara WebCam TimeLapse capture software.
 * Copyright (C) 2012 AdaraProjectTeam
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package adara.plugins;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Observable;
import java.util.Observer;

import org.apache.log4j.Logger;

/**
 * The abstract class which implement the basics for a plugin.
 * @author Andrei Ermicioi (aka erani) <andrei.ermicioi@gmail.com>
 *
 */
public abstract class Plugin extends Thread implements Observer {
	
	private static final Logger logger = Logger.getLogger(Plugin.class);
	private static final int MAX_ERROR_COUNT = 3;
	
	private int maxErrors;
	private int errorCount;
	private boolean keepAlive;
	
	public Plugin() {
		this.setDaemon(true);
		
		this.keepAlive = false;
		this.maxErrors = MAX_ERROR_COUNT;
		this.errorCount = 0;
	}
	
	public abstract void init(int timegap, File storage);
	protected abstract void update(BufferedImage image);
	protected abstract void process();
	
	@Override
	public void update(Observable caller, Object obj) {
		if (! (obj instanceof BufferedImage)) return;
		
		try {
			this.update((BufferedImage)obj);
			errorCount = 0;
		} catch (Exception e) {
			logger.error("Plugin execution error", e);
			errorCount++;
			
			if (errorCount >= maxErrors) {
				this.detachPlugin(caller);
			}
		}
		
		this.unfreez();
	}
	
	@Override
	public void run() {
		keepAlive = true;
		
		while (keepAlive) {
			this.freez();
			this.process();
		}
	}
	
	public void close() {
		keepAlive = false;
		this.unfreez();
	}
	
	private void detachPlugin(Observable caller) {
		logger.info("Dettaching plugin " + this.getClass().getName() + " due to number of errors has exceeded");
		
		caller.deleteObserver(this);
		this.close();
	}
	
	private void freez() {
		synchronized (this) {
			try {
				this.wait();
			} catch (InterruptedException e) { }
		}
	}
	
	private void unfreez() {
		synchronized (this) {
			this.notify();
		}
	}
}
